# system
import csv
import StringIO

# appengine
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

# local
import base

class UploadPage(webapp.RequestHandler):
  def parse(self, datafile, enc="utf16"):
    utf8_data = unicode(datafile, enc).encode('utf8')
    reader = csv.reader(StringIO.StringIO(utf8_data), 'excel-tab')
    line = 0
    fields = ("Name", "Sex", "Age", "Contact", "Address", "Unit", "Status",
              "Other", "Hospital", "Section", "HospitalContact", "Source")
    field_map = {}
    try:
      for row in reader:
        if line == 0:
          for id, field in zip(xrange(len(row)), row):
            field_map[field] = id
          for field in fields:
            if not (field in field_map):
              return "The first line must contain %s: %s" % (', '.join(fields), row)
        else:
          row_unicode = [unicode(x, 'utf8') for x in row]
          if len(row_unicode) < len(fields):
            row_unicode.extend([u""] * (len(fields) - len(row_unicode)))
          person = base.Person() 
          person.name = row_unicode[field_map['Name']]
          person.sex = row_unicode[field_map['Sex']]
          person.age = row_unicode[field_map['Age']]
          person.contact = row_unicode[field_map['Contact']]
          person.address = row_unicode[field_map['Address']]
          person.unit = row_unicode[field_map['Unit']]
          person.status = row_unicode[field_map['Status']]
          person.other = row_unicode[field_map['Other']]
          person.hospital = row_unicode[field_map['Hospital']]
          person.section = row_unicode[field_map['Section']]
          person.hospital_contact = row_unicode[field_map['HospitalContact']]
          person.source = row_unicode[field_map['Source']]
          person.put()
        line += 1
    except csv.Error, e:
      return "Error at line %d: %s" % (reader.line_num, e)
    return "Successfully imported %d persons." % (line - 1)
  
  def post(self):
    # security check
    if not users.is_current_user_admin():
      self.error(403)
      return
    template_values = base.GetPersonsTemplate(self, None)
    message = self.parse(self.request.get('upload'))
    template_values['message'] = message
    path = base.GetTemplatePath('upload.html')
    self.response.out.write(template.render(path, template_values))

  def get(self):
    template_values = base.GetPersonsTemplate(self, None)
    path = base.GetTemplatePath('upload.html')
    self.response.out.write(template.render(path, template_values))

